package FileDAO;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;

/**
 * DAO de base
 * @author vbergout
 *
 * @param <T>
 * @param <PK>
 */
public class GenericDao<T, PK extends Serializable> {
	/**
	 * Logger for this class
	 */
	private static final Logger log = LoggerFactory.getLogger(GenericDao.class);
	
	/**
	 * Hibernate Session
	 */
    protected Session session;
	    
    private Class<T> type;
    
    /**
     * Constructeur
     * @param type Type d'objet
     * @param session Session Hibernate
     */
    public GenericDao(Class<T> type, Session session) {
    	this.session = session;
        this.type = type;
    }
    
    /* (non-Javadoc)
     * @see com.atosorigin.bea.db.dao.GenericDao#insert(java.lang.Object)
     */
    @SuppressWarnings("unchecked")
	public PK insert(T object){
		log.debug("insert(T object=" + object + ") - start");
		PK returnPK = (PK) session.save(object);
		log.debug("insert(T) - end");
        return returnPK;    	
    }
    
    
    /* (non-Javadoc)
     * @see com.atosorigin.bea.db.dao.GenericDao#read(java.io.Serializable)
     */
    @SuppressWarnings("unchecked")
	public T find(PK id){
		log.debug("find(PK id=" + id + ") - start");		
		T returnT = (T) session.get(type, id);
		log.debug("find(PK) - end");
        return returnT;
    }
 
    /* (non-Javadoc)
     * @see com.atosorigin.bea.db.dao.GenericDao#readAll()
     */
    @SuppressWarnings("unchecked")
	public List<T> findAll(){
		log.debug("findAll() - start");
        Criteria crit = session.createCriteria(type);
		List<T> returnList = crit.list();
		log.debug("findAll() - end");
        return returnList;    	
    }
 
    /* (non-Javadoc)
     * @see com.atosorigin.bea.db.dao.GenericDao#update(java.lang.Object)
     */
    public void update(T o){
		log.debug("update(T o=" + o + ") - start");	
    	session.update(o);
		log.debug("update(T) - end");
    }
 
    /* (non-Javadoc)
     * @see com.atosorigin.bea.db.dao.GenericDao#delete(java.lang.Object)
     */
    public void delete(T o){
		log.debug("delete(T o=" + o + ") - start");
    	session.delete(o);
		log.debug("delete(T) - end");
    }
}
